/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.incad.psh.pshassign.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author alberto
 */
public class PathInfo extends HttpServlet {

    private Logger logger = Logger.getLogger(this.getClass().getName());
    DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Document dom = search(request.getParameter("path"));
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath;
            XPathExpression expr;
            xpath = factory.newXPath();
            String xPathStr = "response/result/doc/arr[@name='csPrefLabel']/str";
            expr = xpath.compile(xPathStr);
            NodeList nodes = (NodeList) expr.evaluate(dom, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (node != null && node.hasChildNodes()) {
                    out.print("/"+node.getFirstChild().getNodeValue());
                }
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "Error: ", ex);
            out.print(ex);
        } finally {
            out.close();
        }
    }

    private Document search(String path) throws Exception {
        String q = ""; // = path.substring(1).replaceAll("/", "+OR+id:");
        String[] ids = path.substring(1).split("/");
        for(int i=0; i<ids.length; i++){
            String id = ids[i];
            if(i>0){
                q += "+OR+";
            }
            q += "id:"+id + "^" + (10-i);
        }
        String urlStr = Options.getOption("psh", "solr") + "/select?fl=csPrefLabel&q=" + q + "";
        java.net.URL url = new java.net.URL(urlStr);

        df.setNamespaceAware(false);
        DocumentBuilder builder = df.newDocumentBuilder();

        InputStream is;
        is = url.openStream();
        return builder.parse(is);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
